<script setup lang="ts">
import { reactive, onMounted, ref } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { Edit, Delete, Select, Close } from '@element-plus/icons-vue'
import { queryOrderNo, delOrderNo, saveOrderNo, selectModule } from '@/api/develop'
import { useAppStore } from '@/store/modules/app'
import { useI18n } from '@/hooks/web/useI18n'
import { useLocaleStoreWithOut } from '@/store/modules/locale'
import { getZhHKAndPinyin, getZhCNAndPinyin } from '@/api/common'
import { Paging } from '@/config/public'
import { ModuleTree } from '@/components/Tree'

defineOptions({
  name: 'OrderNoList'
})

const appStore = useAppStore()
const { t } = useI18n()
const formRef = ref()
const localeStore = useLocaleStoreWithOut()
const curLang = localeStore.getCurrentLocale.lang
//新建记录的默认值
const initRecord = {
  id: null,
  identifier: '',
  moduleId: '',
  enName: '',
  hkName: '',
  orderName: '',
  rules: 'PREFIX{yyMM}-{NO}',
  remark: '',
  initVal: 1,
  step: 1,
  currentVal: 0,
  noLen: 5,
  resetType: 0,
  status: 1,
  seq: 1
}
const state = reactive({
  searchKey: '',
  // 表格數據
  tableView: [{}],
  // 分頁相關屬性
  totalCount: 0,
  pageSizes: Paging.sizes,
  queryBody: {
    key: '',
    pageNo: 1,
    pageSize: Paging.defaultSize,
    params: {
      'Q_sn.status_I_LT': 4
    },
    sortField: '',
    sortOrder: ''
  },
  // 对话框绑定的数据
  dialogVisible: false,
  dialogTitle: '',
  dialogForm: { ...initRecord },
  dialogRule: {
    orderName: [
      {
        required: true,
        message: t('orderNo.name') + t('common.notEmpty'),
        trigger: ['blur']
      }
    ],
    rules: [
      {
        required: true,
        message: t('orderNo.rules') + t('common.notEmpty'),
        trigger: ['blur']
      }
    ],
    identifier: [
      {
        required: true,
        message: t('orderNo.identifier') + t('common.notEmpty'),
        trigger: ['blur']
      }
    ],
    moduleId: [
      {
        required: true,
        message: t('orderNo.module') + t('common.notEmpty'),
        trigger: ['blur', 'change']
      }
    ]
  },
  modNameField: 'moduleName',
  orderNameField: 'orderName',
  lstModNameField: 'moduleName',
  curModuleId: '',
  moduleList: [{}]
})
onMounted(async () => {
  if (curLang == 'en') {
    state.modNameField = 'enName'
    state.orderNameField = 'enName'
    state.lstModNameField = 'enModuleName'
  } else if (curLang == 'zh_HK') {
    state.modNameField = 'hkName'
    state.orderNameField = 'hkName'
    state.lstModNameField = 'hkModuleName'
  }
  state.moduleList = await selectModule()
  init()
})
const changePage = (page) => {
  state.queryBody.pageNo = page
  init()
}
const changePageSize = (pageSize) => {
  state.queryBody.pageSize = pageSize
  state.queryBody.pageNo = 1
  init()
}

// 保存当前记录
const save = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      await saveOrderNo(state.dialogForm).then((res) => {
        const result = res as any
        if (res) {
          ElMessage.success(t(result.message))
          state.dialogVisible = false
          init()
        }
      })
    }
  })
}
// 刪除当前记录
const deleteOne = (row) => {
  ElMessageBox.confirm(t('common.delMessage'), t('common.warning'), {
    confirmButtonText: t('common.ok'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  })
    .then(async () => {
      await delOrderNo(row.id)
      init()
    })
    .catch(() => {})
}
// 显示对话框
const openDialog = (type, row) => {
  if (type == 'add') {
    state.dialogForm = { ...initRecord }
    state.dialogForm.moduleId = state.curModuleId
    state.dialogTitle = t('common.add') + ' ' + t('orderNo.orderNo')
  } else {
    //修改
    state.dialogForm = row
    state.dialogTitle = t('common.modify') + ' ' + t('orderNo.orderNo')
  }
  state.dialogVisible = true
}
// 搜索
const handleSearch = () => {
  state.queryBody.key = state.searchKey
  init()
}
//重置查询
const resetSearch = () => {
  state.searchKey = ''
  state.queryBody.params['Q_sn.module_id_S_IN'] = ''
  handleSearch()
}
//点击模块树节点
const handleNodeClick = (data) => {
  state.queryBody.params['Q_sn.module_id_S_IN'] = data
  state.curModuleId = data.split(',')[0]
  handleSearch()
}

//渲染页面的接口
const init = async () => {
  appStore.setFooter(false)
  state.tableView = []
  await queryOrderNo(state.queryBody)
    .then((res) => {
      const result = res as any
      var data = result.result.data
      state.tableView = data
      state.totalCount = result.result.totalCount
    })
    .catch(() => {})
}

/**
 * @description 当繁体中文为空时，转换简体中文为繁体中文
 * @author Elwin ZHANG
 * @date 2023-03-21 10:33
 */
const zhHKAndPinyin = async (event) => {
  const text = event.target.value
  if (!text || text.length == 0) {
    return
  }
  //繁体中文为空时才自动转换
  if (state.dialogForm.hkName.length > 0) {
    return
  }
  let data = (await getZhHKAndPinyin(text, 50)) as any
  state.dialogForm.hkName = data.data.zhHK
  //如果英文字段为空，默认为拼音
  if (state.dialogForm.enName.length == 0) {
    state.dialogForm.enName = data.data.pinyin
  }
  if (state.dialogForm.identifier.length == 0) {
    state.dialogForm.identifier = data.data.pinyin.replace(/\s+/g, '')
  }
  formRef.value.clearValidate(['hkName', 'identifier', 'enName'])
}

/**
 * @description 当简体中文为空时，转换繁体中文为简体中文
 * @author Elwin ZHANG
 * @date 2023-03-21 10:33
 */
const zhCNAndPinyin = async (event) => {
  const text = event.target.value
  if (!text || text.length == 0) {
    return
  }
  //简体中文为空时才自动转换
  if (state.dialogForm.orderName.length > 0) {
    return
  }
  let data = (await getZhCNAndPinyin(text, 50)) as any
  state.dialogForm.orderName = data.data.zhCN
  //如果英文字段为空，默认为拼音
  if (state.dialogForm.enName.length == 0) {
    state.dialogForm.enName = data.data.pinyin
  }
  if (state.dialogForm.identifier.length == 0) {
    state.dialogForm.identifier = data.data.pinyin.replace(/\s+/g, '')
  }
  formRef.value.clearValidate(['orderName', 'identifier', 'enName'])
}
</script>
<template>
  <div>
    <!-- 搜索條件卡片 -->
    <el-card class="box-card">
      <el-row :gutter="10" style="padding: 5px 5px; line-height: 28px" align="middle">
        <el-col :sm="5" :md="4" style="text-align: right">{{ $t('common.searchKey') }}</el-col>
        <el-col :sm="19" :md="12" style="text-align: left">
          <el-input
            v-model="state.searchKey"
            @keyup.enter="handleSearch"
            :placeholder="
              $t('common.inputText') +
              $t('orderNo.name') +
              '/' +
              $t('orderNo.identifier') +
              '/' +
              $t('common.remark')
            "
          />
        </el-col>
        <el-col :sm="24" :md="8" style="text-align: right">
          <div style="margin-right: -5px">
            <el-button @click="handleSearch" type="primary" size="small" plain
              ><Icon icon="ic:outline-search" /><span>{{ $t('common.query') }}</span></el-button
            >
            <el-button @click="resetSearch" type="info" size="small" plain>
              <Icon icon="icon-park-solid:clear-format" /><span>{{
                $t('common.reset')
              }}</span></el-button
            >
            <el-button type="success" size="small" plain @click="openDialog('add', {})">
              <Icon icon="material-symbols:add-circle-rounded" /><span>{{ $t('common.add') }}</span>
            </el-button>
          </div>
        </el-col>
      </el-row>
    </el-card>
    <el-container class="mainArea">
      <el-aside width="200px">
        <ModuleTree @node-click="handleNodeClick" />
      </el-aside>
      <el-main class="formcard">
        <!-- 搜索結果表格 -->
        <el-table
          :data="state.tableView"
          tooltip-effect="light"
          style="width: 100%; border: 1px solid #ddd; font-size: 12px"
          stripe
          row-key="id"
          default-expand-all
          :header-cell-style="{
            background: 'var(--el-color-primary-light-9)',
            color: '#409eff'
          }"
        >
          <el-table-column type="index" min-width="60">
            <template #header>
              <div style="margin-bottom: -10px">
                <Icon
                  icon="ant-design:field-number-outlined"
                  size="24"
                  :title="$t('common.number')"
              /></div>
            </template>
          </el-table-column>
          <el-table-column
            :prop="state.orderNameField"
            :label="$t('orderNo.name')"
            show-overflow-tooltip
            min-width="120"
          />
          <el-table-column prop="identifier" :label="$t('orderNo.identifier')" min-width="90" />
          <el-table-column
            :prop="state.lstModNameField"
            :label="$t('orderNo.module')"
            min-width="120"
          />
          <el-table-column
            prop="rules"
            :label="$t('orderNo.rules')"
            min-width="180"
            show-overflow-tooltip
          />
          <el-table-column
            prop="noLen"
            :label="$t('orderNo.noLength')"
            min-width="90"
            align="center"
          />
          <el-table-column
            prop="currentVal"
            :label="$t('orderNo.curVal')"
            min-width="90"
            align="center"
          />
          <el-table-column prop="step" :label="$t('orderNo.step')" min-width="90" align="center" />
          <el-table-column prop="status" :label="$t('common.status')" min-width="80" align="center">
            <template #default="{ row }">
              <span v-if="row.status == 1">{{ $t('group.activated') }}</span>
              <span v-else>{{ $t('group.disabled') }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" :label="$t('common.operation')" width="120">
            <template #default="{ row }">
              <el-button
                type="primary"
                plain
                circle
                size="small"
                :title="$t('common.modify')"
                @click="openDialog('edit', row)"
              >
                <el-icon>
                  <Edit />
                </el-icon>
              </el-button>
              <el-button
                type="danger"
                plain
                circle
                size="small"
                :title="$t('common.delete')"
                v-if="!row.children"
                @click="deleteOne(row)"
              >
                <el-icon>
                  <Delete />
                </el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分頁器 -->
        <div class="demo-pagination-block"
          ><el-pagination
            v-model:currentPage="state.queryBody.pageNo"
            v-model:page-size="state.queryBody.pageSize"
            @current-change="changePage"
            @size-change="changePageSize"
            :page-sizes="state.pageSizes"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="state.totalCount"
        /></div>
      </el-main>
    </el-container>
    <!-- 新增或修改對話框 -->
    <el-dialog v-model="state.dialogVisible" :title="state.dialogTitle" width="600px" draggable>
      <el-form
        ref="formRef"
        :model="state.dialogForm"
        :rules="state.dialogRule"
        label-width="120px"
      >
        <el-form-item :label="$t('orderNo.module')" prop="moduleId">
          <el-select
            v-model="state.dialogForm.moduleId"
            :placeholder="$t('common.selectText')"
            size="default"
          >
            <el-option
              v-for="item in state.moduleList"
              :key="item.moduleId"
              :label="item[state.modNameField]"
              :value="item.moduleId"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('orderNo.name')" prop="orderName">
          <el-input
            v-model="state.dialogForm.orderName"
            :placeholder="$t('common.inputText') + $t('orderNo.name')"
            maxlength="50"
            show-word-limit
            @blur="zhHKAndPinyin($event)"
          />
        </el-form-item>
        <el-form-item :label="$t('common.hkName')" prop="hkName">
          <el-input
            v-model="state.dialogForm.hkName"
            :placeholder="$t('common.inputText') + $t('common.hkName')"
            maxlength="50"
            show-word-limit
            @blur="zhCNAndPinyin($event)"
          />
        </el-form-item>
        <el-form-item :label="$t('common.enName')" prop="enName">
          <el-input
            v-model="state.dialogForm.enName"
            :placeholder="$t('common.inputText') + $t('common.enName')"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item :label="$t('orderNo.identifier')" prop="identifier">
          <el-input
            v-model="state.dialogForm.identifier"
            :placeholder="$t('common.inputText') + $t('orderNo.identifier')"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item :label="$t('common.status')" prop="status">
          <el-switch
            v-model.number="state.dialogForm.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item :label="$t('orderNo.rules')" prop="rules">
          <el-input
            v-model="state.dialogForm.rules"
            :placeholder="$t('common.inputText') + $t('orderNo.rules')"
            maxlength="50"
            show-word-limit
          >
            <template #append>
              <el-popover placement="top" :width="600" trigger="hover">
                <template #reference>
                  <el-button class="m-2">{{ t('orderNo.help') }}</el-button>
                </template>
                <p v-html="$t('orderNo.helpText')"></p>
              </el-popover>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('orderNo.initVal')" prop="initVal">
          <el-input-number
            :min="1"
            :max="999999"
            :step="1"
            v-model="state.dialogForm.initVal"
            :placeholder="$t('common.inputText') + $t('orderNo.initVal')"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item :label="$t('orderNo.step')" prop="step">
          <el-input-number
            :min="1"
            :max="999999"
            :step="1"
            v-model="state.dialogForm.step"
            :placeholder="$t('common.inputText') + $t('orderNo.step')"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item :label="$t('orderNo.noLength')" prop="noLen">
          <el-input-number
            :min="1"
            :max="999999"
            :step="1"
            v-model="state.dialogForm.noLen"
            :placeholder="$t('common.inputText') + $t('orderNo.noLength')"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item :label="$t('orderNo.curVal')" prop="currentVal">
          <el-input
            v-model="state.dialogForm.currentVal"
            disabled
            input-style="text-align: center"
          />
        </el-form-item>
        <el-form-item :label="$t('common.remark')" prop="remark">
          <el-input
            v-model="state.dialogForm.remark"
            :placeholder="$t('common.iptRemarks')"
            type="textarea"
            :autosize="{ minRows: 2 }"
            maxlength="255"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer" style="text-align: center">
          <el-button type="primary" @click="save">
            <el-icon><Select /></el-icon>&nbsp;{{ $t('common.save') }}</el-button
          >
          <el-button @click="state.dialogVisible = false">
            <el-icon> <Close /> </el-icon>&nbsp;{{ $t('common.giveUp') }}</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<style lang="less" scoped>
:deep(.el-card__header) {
  border-bottom: 0;
  box-sizing: border-box;
}

:deep(.el-select .el-option .el-input .el-select-dropdown__item) {
  font-size: 12px;
}

:deep(.el-input__inner) {
  &::placeholder {
    font-size: 12px;
  }
  font-size: 12px;
}

:deep(.el-dialog__body) {
  padding: 10px 50px;
}
:deep(.v-footer) {
  height: 0px;
}
.mainArea {
  height: calc(100vh - 145px);
  overflow-x: hidden;
}
.formcard {
  margin: -12px -19px 0 -15px;
}
// 分頁器樣式
.demo-pagination-block {
  display: flex;
  justify-content: center;
  justify-items: center;
  margin-top: 20px;
  margin-bottom: 20px;
}
:deep(.el-pagination__sizes > .el-select) {
  margin-top: -3px;
}
:deep(.el-pager li) {
  font-size: 12px;
  height: 28px;
  margin-top: -1px;
}
:deep(.el-pagination span:not([class*='suffix'])) {
  font-size: 12px;
}
</style>
